<?php
class User_IndexController extends Zend_Controller_Action {
	
	/**
	 * Users Controller
	 * 
	 * @author Nguyen Manh Hung
	 */
	protected $_arrParam;
	public function init() {
		$this->_arrParam = $this->_request->getParams ();
		$this->view->arrParam = $this->_arrParam;
	}
	
	/**
	 * Action Dang Ky
	 */
	public function signupAction() {
		$layoutPath = APPLICATION_PATH . '/templates/quay';
		
		$option = array (
				'layout' => 'signup',
				
				'layoutPath' => $layoutPath 
		);
		
		Zend_Layout::startMvc ( $option );
		
		$translate = Zend_Registry::get ( 'Zend_Translate' );
		
		$this->view->title = $translate->_ ( "TITLE_USER_REGISTER" );
		
		$this->view->headTitle ( $this->view->title );
		
		$this->view->headMeta ()->appendName ( 'keywords', $translate->_ ( 'FRONT_KEYWORD_PUBLIC' ) )->

		appendName ( 'description', $translate->_ ( 'FRONT_DESCRIPTION_PUBLIC' ) );
		
		$form = new User_Form_Register ();
		
		$back = $form->getElement ( 'back' );
		
		$back->setAttrib ( 'onclick', "window.location='" . $this->getFrontController ()->getBaseUrl () . "';" );
		
		$this->view->form = $form;
		
		if ($this->_request->isPost ()) {
			
			$gender = $this->getRequest ()->getPost ( 'title' );
			
			$username = trim ( $this->getRequest ()->getPost ( 'username' ) );
			
			$password = $this->getRequest ()->getPost ( 'password' );
			
			$email = trim ( $this->getRequest ()->getPost ( 'email' ) );
			
			$firstName = trim ( $this->getRequest ()->getPost ( 'first_name' ) );
			
			$lastName = trim ( $this->getRequest ()->getPost ( 'last_name' ) );
			
			$email = strtolower ( $email );
			
			if (! Zend_Validate::is ( $firstName, 'NotEmpty' ))
				
				$messages [] = array (
						
						'text' => $translate->_ ( "TEXT_VALIDATOR_USER_FIRSTNAME_EMPTY" ),
						
						'type' => 'errormsg' 
				);
			
			if (! Zend_Validate::is ( $lastName, 'NotEmpty' ))
				
				$messages [] = array (
						
						'text' => $translate->_ ( "TEXT_VALIDATOR_USER_LASTNAME_EMPTY" ),
						
						'type' => 'errormsg' 
				);
			
			if (! Zend_Validate::is ( $username, 'StringLength', array (
					'min' => 6,
					'max' => 12 
			) ))
				
				$messages [] = array (
						
						'text' => $translate->_ ( "TEXT_VALIDATOR_USER_USERNAME_EMPTY" ),
						
						'type' => 'errormsg' 
				);
			
			if (! $this->validate_alphanumeric_underscore ( $username )) {
				
				$messages [] = array (
						
						'text' => $translate->_ ( "TEXT_VALIDATOR_USER_USERNAME_REGEX" ),
						
						'type' => 'errormsg' 
				);
			}
			
			if (! Zend_Validate::is ( $password, 'StringLength', array (
					'min' => 6,
					'max' => 20 
			) ))
				
				$messages [] = array (
						
						'text' => $translate->_ ( "TEXT_VALIDATOR_USER_PASSWORD_EMPTY" ),
						
						'type' => 'errormsg' 
				);
			
			if (! Zend_Validate::is ( $email, 'EmailAddress' ))
				
				$messages [] = array (
						
						'text' => $translate->_ ( "TEXT_VALIDATOR_USER_EMAIL_INVALID" ),
						
						'type' => 'errormsg' 
				);
			
			if (count ( $messages ) == 0) {
				
				$userModel = new User_Model_Accounts ();
				
				$checkUsername = $userModel->fetchUser ( array (
						'username' => $username 
				) );
				
				$checkEmail = $userModel->fetchUser ( array (
						'email' => $email 
				) );
				
				if (count ( $checkUsername ) > 0 || count ( $checkEmail ) > 0) {
					
					if (count ( $checkEmail ) > 0) {
						
						$messages [] = array (
								
								'text' => $translate->_ ( 'TEXT_VALIDATOR_EMAIL_USED' ),
								
								'type' => 'errormsg' 
						);
					} else {
						
						$messages [] = array (
								
								'text' => $translate->_ ( 'TEXT_VALIDATOR_USERNAME_USED' ),
								
								'type' => 'errormsg' 
						);
					}
				} else {
					
					$password = md5 ( $password );
					
					$us = strtolower ( $username );
					
					$accountId = $userModel->createUser ( $firstName, $lastName, $us, $password, $email, $gender );
					
					$cache = Zend_Registry::get ( 'cache' );
					
					$cache->remove ( 'cache_count_user' );
					
					$points = new Zend_Config_Ini ( APPLICATION_PATH . '/configs/default.ini', 'point' );
					
					$pointModel = new Front_Model_Point ();
					
					$pointModel->insertRow ( array (
							'member_id' => $accountId,
							'points' => $points->df 
					) );
					
					$messages [] = array (
							
							'text' => $translate->_ ( 'TEXT_MESSAGE_USER_REGISTER_SUCCESS' ),
							
							'type' => 'success' 
					);
					
					Zend_Loader::loadClass ( 'Zend_Auth_Adapter_DbTable' );
					
					$db = Zend_Db_Table::getDefaultAdapter ();
					
					// create the auth adapter
					
					$authAdapter = new Zend_Auth_Adapter_DbTable ( $db );
					
					$authAdapter->setTableName ( TABLE_MEMBERS );
					
					$authAdapter->setIdentityColumn ( 'username' );
					
					$authAdapter->setCredentialColumn ( 'password' );
					
					// set username, password
					
					$authAdapter->setIdentity ( $us );
					
					$authAdapter->setCredential ( $password );
					
					// xac thuc
					
					$auth = Zend_Auth::getInstance ();
					
					$result = $auth->authenticate ( $authAdapter );
					
					if ($result->isValid ()) {
						
						// luu tru gia tri can thiet cua user
						
						$data = $authAdapter->getResultRowObject ( array (
								'id',
								'username',
								'email',
								'first_name',
								'last_name',
								'active',
								'group',
								'avatarurl' 
						) );
						
						if ($data->active) {
							
							$auth->getStorage ()->write ( $data );
							
							$redirector = new Zend_Controller_Action_Helper_Redirector ();
							
							$redirector->gotoUrlAndExit ( SITE_URL );
						} else {
							
							$auth->clearIdentity ();
							
							$messages [] = array (
									
									'text' => $translate->_ ( "TEXT_LOGIN_FAIL_STATUS" ),
									
									'type' => 'errormsg' 
							);
							
							$this->view->loginMessage = $messages;
						}
					} else {
						
						$messages [] = array (
								
								'text' => $translate->_ ( "TEXT_LOGIN_FAIL" ),
								
								'type' => 'errormsg' 
						);
						
						$this->view->loginMessage = $messages;
					}
				}
			}
			
			$this->view->first_name = $firstName;
			
			$this->view->last_name = $lastName;
			
			$this->view->username = $username;
			
			$this->view->email = $email;
			
			$this->view->loginMessage = $messages;
		}
	}
	
	/**
	 * Action dang nhap
	 */
	public function signinAction() {
		$layoutPath = APPLICATION_PATH . '/templates/quay';
		
		$option = array (
				'layout' => 'signin',
				
				'layoutPath' => $layoutPath 
		);
		
		Zend_Layout::startMvc ( $option );
		
		$translate = Zend_Registry::get ( 'Zend_Translate' );
		
		$this->view->title = $translate->_ ( "TITLE_USER_LOGIN" );
		
		$this->view->headTitle ( $this->view->title );
		
		$this->view->headMeta ()->appendName ( 'keywords', $translate->_ ( 'FRONT_KEYWORD_PUBLIC' ) )->

		appendName ( 'description', $translate->_ ( 'FRONT_DESCRIPTION_PUBLIC' ) );
		
		$form = new User_Form_LoginForm ();
		
		$this->view->form = $form;
		
		if ($this->_request->isPost ()) {
			
			$username = trim ( $this->getRequest ()->getPost ( 'username' ) );
			
			$password = $this->getRequest ()->getPost ( 'password' );
			
			if (! Zend_Validate::is ( $username, 'NotEmpty' ))
				
				$messages [] = array (
						
						'text' => $translate->_ ( 'TEXT_VALIDATOR_EMPTY_USERNAME' ),
						
						'type' => 'errormsg' 
				);
			
			if (! Zend_Validate::is ( $password, 'NotEmpty' ))
				
				$messages [] = array (
						
						'text' => $translate->_ ( 'TEXT_VALIDATOR_EMPTY_PASSWORD' ),
						
						'type' => 'errormsg' 
				);
			
			if (count ( $messages ) == 0) {
				
				// setup Auth adapter
				
				// get default db adapter
				
				Zend_Loader::loadClass ( 'Zend_Auth_Adapter_DbTable' );
				
				$db = Zend_Db_Table::getDefaultAdapter ();
				
				// create the auth adapter
				
				$authAdapter = new Zend_Auth_Adapter_DbTable ( $db );
				
				$authAdapter->setTableName ( TABLE_USERS );
				
				$authAdapter->setIdentityColumn ( 'username' );
				
				$authAdapter->setCredentialColumn ( 'password' );
				
				// set username, password
				
				$password = md5 ( $password );
				
				$us = strtolower ( $username );
				
				$authAdapter->setIdentity ( $us );
				
				$authAdapter->setCredential ( $password );
				
				// xac thuc
				
				$auth = Zend_Auth::getInstance ();
				
				$result = $auth->authenticate ( $authAdapter );
				
				if ($result->isValid ()) {
					
					// luu tru gia tri can thiet cua user
					
					$data = $authAdapter->getResultRowObject ( array (
							'id',
							'username',
							'email',
							'first_name',
							'last_name',
							'active',
							'group',
							'avatarurl' 
					) );
					
					if ($data->active) {
						
						$auth->getStorage ()->write ( $data );
						
						$redirector = new Zend_Controller_Action_Helper_Redirector ();
						
						$redirector->gotoUrlAndExit ( SITE_URL );
					} else {
						
						$auth->clearIdentity ();
						
						$messages [] = array (
								
								'text' => $translate->_ ( "TEXT_LOGIN_FAIL_STATUS" ),
								
								'type' => 'errormsg' 
						);
						
						$this->view->loginMessage = $messages;
					}
				} else {
					
					$messages [] = array (
							
							'text' => $translate->_ ( "TEXT_LOGIN_FAIL" ),
							
							'type' => 'errormsg' 
					);
					
					$this->view->loginMessage = $messages;
				}
			} else {
				
				$this->view->loginMessage = $messages;
			}
		}
	}
	
	/**
	 * Show message login success	 * 
	 * @author Nguyen Manh Hung
	 */
	public function loginsuccessAction() {
		$translate = Zend_Registry::get ( 'Zend_Translate' );
		
		$this->view->title = $translate->_ ( "TITLE_USER_LOGIN" );
		
		$this->view->headTitle ( $this->view->title );
		
		$this->view->headMeta ()->appendName ( 'keywords', $translate->_ ( 'FRONT_KEYWORD_PUBLIC' ) )->

		appendName ( 'description', $translate->_ ( 'FRONT_DESCRIPTION_PUBLIC' ) );
		
		$message = $this->_getParam ( 'message' );
		
		if ($message == 'success') {
			
			$this->view->note = $translate->_ ( 'TEXT_LOGIN_SUCCESS' );
			
			$redirector = new Zend_Controller_Action_Helper_Redirector ();
			
			$redirector->gotoUrlAndExit ( SITE_URL );
		} else {
			
			$redirector = new Zend_Controller_Action_Helper_Redirector ();
			
			$redirector->gotoUrlAndExit ( SITE_URL );
		}
	}
	
	/**
	 * logout action
	 * @author Nguyen Manh Hung
	 */
	public function logoutAction() {
		$authAdapter = Zend_Auth::getInstance ();
		
		$authAdapter->clearIdentity ();
		
		$redirector = new Zend_Controller_Action_Helper_Redirector ();
		
		$redirector->gotoUrlAndExit ( SITE_URL );
	}
	
	/**
	 * Action lay lai mat khau
	 */
	public function fpassAction() {
		$layoutPath = APPLICATION_PATH . '/templates/quay';
		
		$option = array (
				'layout' => 'signin',
				
				'layoutPath' => $layoutPath 
		);
		
		Zend_Layout::startMvc ( $option );
		
		$translate = Zend_Registry::get ( 'Zend_Translate' );
		
		$this->view->title = $translate->_ ( "TITLE_USER_FORGOT_PASS" );
		
		$this->view->headTitle ( $this->view->title );
		
		$this->view->headMeta ()->appendName ( 'keywords', $translate->_ ( 'FRONT_KEYWORD_PUBLIC' ) )->

		appendName ( 'description', $translate->_ ( 'FRONT_DESCRIPTION_PUBLIC' ) );
		
		$form = new User_Form_ResetPass ();
		
		$back = $form->getElement ( 'back' );
		
		$back->setAttrib ( 'onclick', "window.location='" . $this->getFrontController ()->getBaseUrl () . "';" );
		
		$this->view->form = $form;
		
		$authAdapter = Zend_Auth::getInstance ();
		
		if ($authAdapter->hasIdentity ()) {
			
			$redirector = new Zend_Controller_Action_Helper_Redirector ();
			
			$redirector->gotoUrlAndExit ( SITE_URL . '/my-info.html' );
		}
		
		if ($this->_request->isPost ()) {
			
			$email = $this->getRequest ()->getPost ( 'email' );
			
			if (! Zend_Validate::is ( $email, 'EmailAddress' ))
				
				$messages [0] = array (
						
						'text' => $translate->_ ( 'TEXT_VALIDATOR_USER_EMAIL_INVALID' ),
						
						'type' => 'errormsg' 
				);
			
			if (count ( $messages ) == 0) {
				
				$userModel = new User_Model_Accounts ();
				
				$fetchEmail = $userModel->fetchUser ( array (
						'email' => $email 
				) );
				
				$fetchEmail = $fetchEmail->toArray ();
				
				if (count ( $fetchEmail )) {
					
					$newPass = '';
					
					for($i = 0; $i < 6; $i ++) {
						
						$d = rand ( 1, 30 ) % 2;
						
						$newPass .= $d ? chr ( rand ( 65, 90 ) ) : chr ( rand ( 48, 57 ) );
					}
					
					$passToChange = md5 ( $newPass );
					
					$changePass = $userModel->changePass ( $fetchEmail [0] ['id'], $passToChange );
					
					if ($changePass) {
						
						$mail = new Zend_Mail ();
						
						$mail->setBodyHtml ( 'Your password:' . $newPass );
						
						$mail->addTo ( $email );
						
						$mail->setSubject ( 'Gameangrybirds.com: New password' );
						
						$mail->setFrom ( 'Gameangrybirds.com' );
						
						$mail->send ();
						
						$messages [0] = array (
								
								'text' => $translate->_ ( 'TEXT_MESSAGE_USER_RESET_PASS_SUCCESS' ),
								
								'type' => 'success' 
						);
					} else {
						
						$messages [0] = array (
								
								'text' => $translate->_ ( 'TEXT_MESSAGE_USER_RESET_PASS_FAILD' ),
								
								'type' => 'errormsg' 
						);
					}
				} else {
					
					$messages [0] = array (
							
							'text' => $translate->_ ( 'TEXT_MESSAGE_USER_NOT_FOUND_EMAIL' ),
							
							'type' => 'errormsg' 
					);
				}
			}
			
			$this->view->loginMessage = $messages;
		}
	}
	
	protected function validate_alphanumeric_underscore($str) {
		return preg_match ( '/^[A-Za-z0-9_]+$/', $str );
	}
}